package com.example.seakdreamandroid.whiteNoisePlayer;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;

import com.example.seakdreamandroid.Constant;
import com.example.seakdreamandroid.MainActivity;
import com.example.seakdreamandroid.MusicStoryPlayerActivity;
import com.example.seakdreamandroid.entity.AudioInfo;
import com.example.seakdreamandroid.entity.User;
import com.example.seakdreamandroid.whiteNoise.OfficialRecommendation;
import com.example.seakdreamandroid.whiteNoise.SleepFriendCreation;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;

import okhttp3.Call;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/*
杨锐涵 白噪音播放Service
单例模式
 */
public class WhiteNoisePlayerService extends Service {
    //声明一个MediaPlayer引用
    private static MediaPlayer player1,player2,player3;
    private static boolean pre;
    private static User user;
    private static int voice1 = 100,voice2 = 100,voice3 = 100;
    private static List<AudioInfo> audioInfos = new ArrayList<AudioInfo>();
    private static String channel = null;
    private static String channelInfoId = null;
    private static int playState;
    public static final int NONE = 0;
    public static final int PREPARING = 1;
    public static final int PLAYING = 2;
    public static final int PAUSE = 3;
    public static final int ERROR = 4;
    public static final int START_EVENT = 0;
    public static final int PREPARED_EVENT = 1;
    public static final int CONTINUE_EVENT = 2;
    public static final int PAUSE_EVENT = 3;
    public static final int ERROR_EVENT = 4;

    //用来记录注册了注册了事件监听的handler
    private static HashSet<Handler> listenerSet = new HashSet<Handler>();
    //控制器
    private static WhiteNoiseControl controller;
    private boolean autoPlay = true;

    public static int getVoice1() {
        return voice1;
    }

    public static int getVoice2() {
        return voice2;
    }

    public static int getVoice3() {
        return voice3;
    }

    public static List<AudioInfo> getAudioInfos(){
        //我是不是应该在这里来个深拷贝，避免被修改从而影响服务的运行，导致不可预料的错误呢,来个浅拷贝吧
        return new ArrayList<AudioInfo>(audioInfos);
    }

    public static String getChannel(){
        return channel;
    }

    public static String getChannelInfoId(){
        return channelInfoId;
    }

    public static int getPlayState(){
        return playState;
    }

    public static WhiteNoiseControl getController(){
        return controller;
    }
    public static void registerForListener(Handler handler) {
        listenerSet.add(handler);
    }
    public static void removeForListener(Handler handler){
        listenerSet.remove(handler);
    }
    //发送准备完成事件
    private static void sendPreparedEvent(){
        for(Handler handler : listenerSet){
            handler.sendEmptyMessage(1);
        }
    }

    //发送继续播放事件
    private static void sendContinueEvent(){
        for(Handler handler : listenerSet){
            handler.sendEmptyMessage(2);
        }
    }

    //发送暂停播放事件
    private static void sendPauseEvent(){
        for(Handler handler : listenerSet){
            handler.sendEmptyMessage(3);
        }
    }

    //发送开始播放事件
    private static void sendStartEvent(){
        for(Handler handler : listenerSet){
            handler.sendEmptyMessage(0);
        }
    }

    //发送错误事件
    private static void sendErrorEvent(){
        for(Handler handler : listenerSet){
            handler.sendEmptyMessage(4);
        }
    }

    public WhiteNoisePlayerService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        return  new WhiteNoiseControl();
    }

    @Override
    public void onCreate() {
        super.onCreate();
        user = (User)getApplication();
        playState = NONE;
        //创建音乐播放器对象
//        player = new MediaPlayer();
        player1 = new MediaPlayer();
        player2 = new MediaPlayer();
        player3 = new MediaPlayer();
        player1.setLooping(true);
        player2.setLooping(true);
        player3.setLooping(true);
//        addTimer();
        MediaPlayer.OnPreparedListener listener = new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                if(!pre){
                    pre = true;
                    sendPreparedEvent();
                }
                if(autoPlay){
                    mp.start();
                    playState = PLAYING;
                }else{
                    playState = PAUSE;
                }
            }
        };
        player1.setOnPreparedListener(listener);
        player2.setOnPreparedListener(listener);
        player3.setOnPreparedListener(listener);
        controller = new WhiteNoiseControl();
    }

    /**
     * 更新历史记录，删旧增新
     * @param audioInfos，播放的音乐
     */
    private static void updateHistory(List<AudioInfo> audioInfos){
        new Thread(new Runnable() {
            @Override
            public void run() {
                //调用两个同步请求的方法，保证先删后增
                deleteHistory(audioInfos);
                addHistory(audioInfos);
            }
        }).start();
    }

    /**
     * 同步请求，需要单独开启一个线程
     * @param audioInfos，播放的歌曲列表
     */
    private static void deleteHistory(List<AudioInfo> audioInfos) {
        OkHttpClient okHttpClient = new OkHttpClient();
        FormBody.Builder builder = new FormBody.Builder()
                .add("userId",user.getUserId())
                .add("whiteNoise1",audioInfos.get(0).getAudioId());
        if(audioInfos.size()>1)builder.add("whiteNoise2",audioInfos.get(1).getAudioId());
        if(audioInfos.size()>2)builder.add("whiteNoise3",audioInfos.get(2).getAudioId());
        FormBody body = builder.build();
        Request request = new Request.Builder()
                .url(Constant.BASE_URL + "WhiteNoise/deleteHistory")
                .post(body)
                .build();
        Call call = okHttpClient.newCall(request);
        try {
            Response response = call.execute();
            String result = response.body().string();
            JSONObject jsonObject = new JSONObject(result);
            if(jsonObject.getString("code").equals("200")){
                Log.i(WhiteNoisePlayerService.class.getName(),"deleteHistory,成功");
            }else{
                Log.e(WhiteNoisePlayerService.class.getName(),"deleteHistory,失败,服务器返回非正常code");
            }
            response.close();
        } catch (IOException | JSONException e) {
            Log.e(WhiteNoisePlayerService.class.getName(),"deleteHistory,失败,抛出异常");
            e.printStackTrace();
        }
    }

    /**
     * 同步请求，需要单独开启一个线程
     * @param audioInfos，音频列表
     */
    private static void addHistory(List<AudioInfo> audioInfos) {
        Date date = new Date();
        SimpleDateFormat dateFormat= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);
        OkHttpClient okHttpClient = new OkHttpClient();
        FormBody.Builder builder = new FormBody.Builder()
                .add("userId",user.getUserId())
                .add("listenTime", dateFormat.format(date))
                .add("isWhite","白噪音")
                .add("whiteNoise1",audioInfos.get(0).getAudioId());
        if(audioInfos.size()>1)builder.add("whiteNoise2",audioInfos.get(1).getAudioId());
        if(audioInfos.size()>2)builder.add("whiteNoise3",audioInfos.get(2).getAudioId());
        FormBody body = builder.build();
        Request request = new Request.Builder()
                .url(Constant.BASE_URL + "WhiteNoise/createHistory")
                .post(body)
                .build();
        Call call = okHttpClient.newCall(request);
        try {
            Response response = call.execute();
            String result = response.body().string();
            JSONObject jsonObject = new JSONObject(result);
            if(jsonObject.getString("code").equals("200")){
                Log.i(WhiteNoisePlayerService.class.getName(),"createHistory,成功");
            }else{
                Log.e(WhiteNoisePlayerService.class.getName(),"createHistory,失败,服务器返回非正常code");
            }
            response.close();
        } catch (IOException | JSONException e) {
            Log.e(WhiteNoisePlayerService.class.getName(),"createHistory,失败,抛出异常");
            e.printStackTrace();
        }
    }
    //添加计时器用于设置音乐播放器中的播放进度条
//    public void addTimer(){
//        if(timer!=null)timer.cancel();
//        timer = new Timer();
//
//        //如果timer不存在，也就是没有引用实例
//        TimerTask task = new TimerTask() {
//            @Override
//            public void run() {
//                if(player1 == null && player2 == null && player3 == null){
//                    return;
//                }
//                if(player1 != null) {
//                    int duration = player1.getDuration();//获取歌曲总时长
//                    int currentPosition = player1.getCurrentPosition();//获取播放进度
//                    MainActivity.handler.sendEmptyMessage(2);
//                }
//            }
//        };
//        //开始计时任务后的5毫秒，第一次执行task任务，以后每500毫秒（0.5s）执行一次
//        timer.schedule(task,5,500);
//    }
    //Binder是一种跨进程的通信方式
    public class WhiteNoiseControl extends Binder{



        public void setVolume1(int volume){
            volume = (volume < 0)?0:volume;
            volume = (volume > 100)?100:volume;
            voice1 = volume;
            player1.setVolume(volume/100.0f,volume/100.0f);

        }
        public void setVolume2(int volume){
            volume = (volume < 0)?0:volume;
            volume = (volume > 100)?100:volume;
            voice2 = volume;
            player2.setVolume(volume/100.0f,volume/100.0f);
        }
        public void setVolume3(int volume){
            volume = (volume < 0)?0:volume;
            volume = (volume > 100)?100:volume;
            voice3 = volume;
            player3.setVolume(volume/100.0f,volume/100.0f);
        }
        //取消正在准备的音频的自动播放
        public void cancelAutoPlay(){
            if(playState == PREPARING) WhiteNoisePlayerService.this.autoPlay = false;
        }
        public void play(List<AudioInfo> audioInfos, String channel, String channelInfoId, boolean send){
            if(audioInfos == null)return;
            pre = false;
            autoPlay = true;
            user.setWhiteNoiseIsPlay(true);
            user.setMSPIsPlay(false);
            WhiteNoisePlayerService.this.channel = channel;
            WhiteNoisePlayerService.this.channelInfoId = channelInfoId;
            WhiteNoisePlayerService.this.audioInfos = audioInfos;
            String url1 = (audioInfos.size() >= 1)?audioInfos.get(0).getAudioUrl():null;
            String url2 = (audioInfos.size() >= 2)?audioInfos.get(1).getAudioUrl():null;
            String url3 = (audioInfos.size() >= 3)?audioInfos.get(2).getAudioUrl():null;
            if(playState != NONE && playState != PREPARING && playState != PAUSE && playState != PLAYING && playState != ERROR){
                Log.e("WhiteNoisePlayerService","调用play()在错误的状态,playState=" + playState);
                return;
            }
            updateHistory(audioInfos);
            try{
                player1.reset();
                player2.reset();
                player3.reset();
                if (url1 != null) {
                    player1.setDataSource(url1);
                    player1.prepareAsync();
                }
                if (url2 != null){
                    player2.setDataSource(url2);
                    player2.prepareAsync();
                }
                if (url3 != null){
                    player3.setDataSource(url3);
                    player3.prepareAsync();
                }
            }catch(Exception e){
                Log.e(this.getClass().getName(),"prepare失败");
                e.printStackTrace();
                playState = ERROR;
                sendErrorEvent();
            }
            playState = PREPARING;
            if(send)sendStartEvent();
        }
        //下面的暂停继续和退出方法全部调用的是MediaPlayer自带的方法
        public void pausePlay(boolean send){
            if(playState != PLAYING){
                Log.e("WhiteNoisePlayerService","调用pausePlay()在错误的状态,playState=" + playState);
                return;
            }
            playState = PAUSE;
            player1.pause();//暂停播放音乐
            player2.pause();//暂停播放音乐
            player3.pause();//暂停播放音乐
            if(send)sendPauseEvent();
        }
        public void continuePlay(boolean send){
            user.setWhiteNoiseIsPlay(true);
            user.setMSPIsPlay(false);
            if(playState != PAUSE){
                Log.e("WhiteNoisePlayerService","调用continuePlay()在错误的状态,playState=" + playState);
                return;
            }
            updateHistory(audioInfos);
            playState = PLAYING;
            player1.start();//继续播放音乐
            player2.start();//继续播放音乐
            player3.start();//继续播放音乐
            if(send)sendContinueEvent();
        }

//        public void seekTo(int progress){
//            player1.seekTo(progress);//设置音乐的播放位置
//            player2.seekTo(progress);//设置音乐的播放位置
//            player3.seekTo(progress);//设置音乐的播放位置
//        }
    }


    //销毁多媒体播放器
    @Override
    public void onDestroy() {
        Log.e(WhiteNoisePlayerService.class.getName(),"onDestory()");
        super.onDestroy();
        player1.stop();
        player2.stop();
        player3.stop();
        player1.release();//释放占用的资源
        player2.release();//释放占用的资源
        player3.release();//释放占用的资源
        player1=null;//将player置为空
        player2=null;//将player置为空
        player3=null;//将player置为空
    }

    public void continuePlay1(){

    }

    public void continuePlay2(){

    }

    public void continuePlay3(){

    }

    public void pause1(){

    }

    public void pause2(){

    }

    public void pause3(){
        
    }
//    //销毁多媒体播放器
//    @Override
//    public void onDestroy() {
//        super.onDestroy();
//        if(player==null) return;
//        if(player.isPlaying()) player.stop();//停止播放音乐
//        player.release();//释放占用的资源
//        player=null;//将player置为空
//    }
}